<?php

namespace App\Admin\Forms;

use App\Models\User;
use App\Models\UserBalance;
use App\Models\UserBalanceFlow;
use Carbon\Carbon;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class Consume extends Form implements LazyRenderable
{
    use LazyWidget;
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        // dump($input);

        // return $this->response()->error('Your error message.');

        $userId = $this->payload['user_id'] ?? null;
        if (!$userId) {
            return $this->response()->error('user_id 参数错误，请联系开发人员');
        }

        $user = User::find($userId);

        if (!$user) {
            return $this->response()->error('用户不存在，请联系开发人员');
        }

        $title = $input['title'] ?? null;
        if (!$title) {
            return $this->response()->error('请填写消费项目');
        }

        $balance = $input['balance'] ?? 0;
        if (empty($balance)) {
            return $this->response()->error('请填写消费金额');
        }

        $operator = $input['operator'] ?? 0;
        if (empty($operator)) {
            return $this->response()->error('请选择服务人员');
        }

        $userBalance = UserBalance::where('user_id', $userId)
            ->get()->first();

        if ($balance > $userBalance->balance) {
            return $this->response()->error('余额不足，请先充值');
        }

        DB::beginTransaction();
        try {

            $rest = $userBalance->balance - $balance;

            $flow = new UserBalanceFlow();
            $flow->user_id = $userId;
            $flow->title = $title;
            $flow->type = 1; // 1 是消费
            $flow->balance = $balance;
            $flow->balance_rest = $rest;
            $flow->operator = $operator;
            $flow->comment = $input['comment'];
            $flow->created_at = $input['created_at'];
            $flow->save();

            // 更新余额
            $userBalance->balance = $rest;
            $userBalance->save();

            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            return $this->response()->error($e->getMessage());
        }

        return $this
				->response()
				->success('添加成功')
				->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->date('created_at', '消费日期')->default(Carbon::now()->format('Y-m-d'));
        $this->text('title', '消费项目')->required();
        $this->decimal('balance', '消费金额')->required();
        $this->select('operator', '服务人员')->options([
            '峰' => '峰',
            '颜' => '颜',
            '潘' => '潘'
        ])->required();
        $this->textarea('comment');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [];
    }
}
